package com.dibang.app.view;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.AttributeSet;
import android.view.View;

import com.yinglan.scrolllayout.ScrollLayout;

/**
 * Created by wxl on 2019/7/22.
 */

public class UpScrollLayout extends ScrollLayout {


    public UpScrollLayout(@NonNull Context context) {
        super(context);
    }

    public UpScrollLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public UpScrollLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    @Override
    public void setAssociatedRecyclerView(RecyclerView recyclerView) {
        recyclerView.addOnScrollListener(associatedRecyclerViewListener);
    }

    private void updateRecyclerViewScrollState(RecyclerView recyclerView) {
        if (recyclerView.getChildCount() == 0) {
            setDraggable(true);
        } else {
            RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
            int[] i = new int[1];
            if (layoutManager instanceof LinearLayoutManager || layoutManager instanceof GridLayoutManager) {
                i[0] = ((LinearLayoutManager) layoutManager).findFirstVisibleItemPosition();
            } else if (layoutManager instanceof StaggeredGridLayoutManager) {
                i = null;
                i = ((StaggeredGridLayoutManager) layoutManager).findFirstVisibleItemPositions(i);
            }
            if (i[0] == 0) {
                View firstChild = recyclerView.getChildAt(0);
                if (firstChild.getTop() == recyclerView.getPaddingTop()) {
                    setDraggable(false);
                    return;
                }
            }
            setDraggable(false);
        }
    }

    private final RecyclerView.OnScrollListener associatedRecyclerViewListener =
            new RecyclerView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                    super.onScrollStateChanged(recyclerView, newState);
                    updateRecyclerViewScrollState(recyclerView);
                }

                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);
                    updateRecyclerViewScrollState(recyclerView);
                }
            };
}
